package com.md.api.common.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.nio.charset.StandardCharsets;

/**
 * 地址转经纬度（使用高德地图获取地址信息的经纬度）
 */
@Slf4j
public class TiandituUtil {
    /**
     * Key
     */
    private static String KEY="c78bbac108eece628ec1218c0ebb9d17";
//    http://api.tianditu.gov.cn/v2/search?postStr={"keyWord":"北京大学","level":12,"mapBound":"116.02524,39.83833,116.65592,39.99185","queryType":1,"start":0,"count":10}&type=query&tk=您的密钥
    public  static String GD_URL="http://api.tianditu.gov.cn/geocoder?ds={\"keyWord\":\"%s\"}&tk=%s";
    public  static String TIP_URL="https://restapi.amap.com/v3/assistant/inputtips?keywords=%s&adcode=%s&key=%s";

    private static String BASE_DISTANCE = "http://restapi.amap.com/v3/distance?type=0&key=%s&origins=%s&destination=%s";

    /**
     * 成功标识
     */
    private static String SUCCESS_FLAG="1";

    /**
     * 根据地址获取对应的经纬度信息
     * @param address
     * @return
     */
    public static String getLonAndLatByAddress(String address){
        String baseUrl = "http://api.tianditu.gov.cn/geocoder";
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUrl)
                .queryParam("ds", "{\"keyWord\":\""+address+"\"}")
                .queryParam("tk", KEY);
        String url = builder.toUriString();

        String responseBody = HttpUtils.doGet(url);
        log.info("地址：{},获取对应的经纬度信息返回：{}",address,responseBody);
        if (responseBody.contains("ä")){
            byte[] utf8Bytes = responseBody.getBytes(StandardCharsets.ISO_8859_1);
            // 使用UTF-8字符集创建一个新的String
            String utf8String = new String(utf8Bytes, StandardCharsets.UTF_8);
            responseBody = utf8String;
            log.info("地址：{},存在乱码，解析后：{}",address,utf8String);
        }
        JSONObject jsonObject = JSONObject.parseObject(responseBody);
        JSONObject location = JSONObject.parseObject(jsonObject.get("location").toString());
        return location.getString("lon")+","+location.getString("lat");
    }

    public static JSONArray getAddressTip(String address,String adcode){
        String baseUrl = "http://api.tianditu.gov.cn/v2/search";
        JSONObject paramJson = new JSONObject();
        paramJson.put("keyWord",address);
        paramJson.put("level",12);
        paramJson.put("specify",adcode);
        paramJson.put("queryType",12);
        paramJson.put("start",0);
        paramJson.put("count",10);
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUrl)
                .queryParam("postStr", paramJson.toJSONString())
                .queryParam("tk", KEY)
                .queryParam("type", "query");
        String url = builder.toUriString();
        String responseBody = HttpUtils.doGet(url);
        log.info("地址：{},普通搜索信息返回：{}",address,responseBody);
        if (responseBody.contains("ä")){
            byte[] utf8Bytes = responseBody.getBytes(StandardCharsets.ISO_8859_1);
            // 使用UTF-8字符集创建一个新的String
            String utf8String = new String(utf8Bytes, StandardCharsets.UTF_8);
            responseBody = utf8String;
            log.info("地址：{},存在乱码，解析后：{}",address,utf8String);
        }
        JSONObject jsonObject = JSONObject.parseObject(responseBody);
        JSONArray array = jsonObject.getJSONArray("pois");
        for(int i=0;i<array.size();i++){
            array.getJSONObject(i).put("location",array.getJSONObject(i).get("lonlat"));
        }
        return array;
    }


//    public static String getDistance(String origins, String destination) {
//        String baseUrl = "http://api.tianditu.gov.cn/drive";
//        JSONObject paramJson = new JSONObject();
//        paramJson.put("orig",origins);
//        paramJson.put("dest",destination);
//        paramJson.put("style",0);
//        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUrl)
//                .queryParam("postStr", paramJson.toJSONString())
//                .queryParam("type", "search")
//                .queryParam("tk", KEY);
//        String url = builder.toUriString();
//
//        String responseBody = HttpUtils.doGet(url);
//        JSONObject jsonObject = JSONObject.parseObject(responseBody);
////        log.info("地址：{},获取对应的经纬度信息返回：{}",address,jsonObject.toJSONString());
//        JSONObject location = JSONObject.parseObject(jsonObject.get("location").toString());
//        return location.getString("lon")+","+location.getString("lat");
//    }

    /**
     * @return 距离计算，单位m
     */
    public static Double getDistance(String origins, String destination) {

        double longitude1 = Double.valueOf(origins.split(",")[0]);
        double latitude1=Double.valueOf(origins.split(",")[1]);
        double longitude2=Double.valueOf(destination.split(",")[0]);
        double latitude2=Double.valueOf(destination.split(",")[1]);


        if (longitude1 == 0 || latitude1 == 0 || latitude2 == 0 || longitude2 == 0) {
            return -1.0;
        }
        longitude1 *= 0.01745329251994329;
        latitude1 *= 0.01745329251994329;
        longitude2 *= 0.01745329251994329;
        latitude2 *= 0.01745329251994329;
        double var1 = Math.sin(longitude1);
        double var2 = Math.sin(latitude1);
        double var3 = Math.cos(longitude1);
        double var4 = Math.cos(latitude1);
        double var5 = Math.sin(longitude2);
        double var6 = Math.sin(latitude2);
        double var7 = Math.cos(longitude2);
        double var8 = Math.cos(latitude2);
        double[] var10 = new double[3];
        double[] var20 = new double[3];
        var10[0] = var4 * var3;
        var10[1] = var4 * var1;
        var10[2] = var2;
        var20[0] = var8 * var7;
        var20[1] = var8 * var5;
        var20[2] = var6;

        return Math.asin(Math.sqrt((var10[0] - var20[0]) * (var10[0] - var20[0]) + (var10[1] - var20[1]) * (var10[1] - var20[1]) + (var10[2] - var20[2]) * (var10[2] - var20[2])) / 2.0) * 1.27420015798544E7;
        // 结果四舍五入 保留2位小数
        //return new BigDecimal(distance).setScale(2, RoundingMode.HALF_UP).doubleValue();
    }

    //    http://api.tianditu.gov.cn/v2/search?postStr={"keyWord":"北京大学","level":12,"mapBound":"-180,-90,180,90","queryType":1,"start":0,"count":10}&type=query
    public static void main(String[] args) {
        String location=getLonAndLatByAddress("重庆重庆市南岸区千方产业园5-2-4");
        System.out.println("经纬度：" + location);
//        System.out.println(getAddressTip("重庆南岸区通江大道","156500000"));
//        System.out.println("当前城市：" + IpUtil.getAddressByIP());
//        System.out.println("距离：" + getDistance("106.470186,29.539380","106.470186,29.539380"));
//        System.out.println("距离：" + getDistance("106.470186,29.539380","106.374393,29.600494"));
//        System.out.println("距离：" + getDistance("106.635767,29.493895","106.635345,29.483302"));

    }
}
